package com.wy.panda.common.sign.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wy.panda.common.sign.AbstractSignValidationHandler;
import com.wy.panda.common.sign.constant.Handler;
import com.wy.panda.common.sign.constant.SignLocationEnum;
import com.wy.panda.common.sign.constant.SubmitWayEnum;
import com.wy.panda.common.util.StringUtils;
import com.wy.panda.exception.PandaCannotHandleException;

/**
 * json方式提交、签名信息再header中
 *
 * @author WangYuan
 * @since 2020年11月5日 下午3:32:32
 */
@Handler(submitWay = SubmitWayEnum.JSON, signLocation = SignLocationEnum.HEADER)
public class JsonAndHeaderSignValidationHandler extends AbstractSignValidationHandler {

	@Override
	protected String getTimestamp(HttpServletRequest request) {
		return request.getHeader(REQUEST_HEADER_TIMESTAMP_KEY);
	}

	@Override
	protected String getAppKey(HttpServletRequest request) {
		return request.getHeader(REQUEST_HEADER_APP_KEY);
	}

	@Override
	protected String getSignMethod(HttpServletRequest request) {
		return request.getHeader(REQUEST_HEADER_SIGN_METHOD_KEY);
	}

	@Override
	protected String getSign(HttpServletRequest request) {
		return request.getHeader(REQUEST_HEADER_SIGN_KEY);
	}

	@Override
	protected Map<String, String> getSignParameter(HttpServletRequest request) {
		StringBuilder bodySb = new StringBuilder();
		try {
			BufferedReader reader = request.getReader();
			
			String tempLineContent = null;
			while(StringUtils.isNotBlank(tempLineContent = reader.readLine())) {
				bodySb.append(tempLineContent);
			}
		} catch (IOException e) {
			throw new PandaCannotHandleException("请求参数解析失败，无法验签。", e);
		}
		
		Map<String, String> params = new HashMap<>();
		
		//添加在header中需要验签的参数
		params.put(REQUEST_HEADER_TIMESTAMP_KEY, getTimestamp(request));
		params.put(REQUEST_HEADER_APP_KEY, getAppKey(request));
		params.put(REQUEST_HEADER_SIGN_METHOD_KEY, getSignMethod(request));
		
		if(bodySb.length() == 0) {
			return params;
		}
		
		JSONObject jsonBody = JSONObject.parseObject(bodySb.toString(), Feature.OrderedField);
		for(Entry<String, Object> entry : jsonBody.entrySet()) {
			if(entry.getValue() == null) {
				params.put(entry.getKey(), null);
				continue;
			}
			
			params.put(entry.getKey(), entry.getValue().toString());
		}
		
		return params;
	}

}
